<template>
  <!-- 确认购买弹窗 -->
  <div id="comfirm-buy" v-show="isShowComfirmBuy">
    <transition mode="out-in" name="comfirm">
      <div class="container" v-if="isShowComfirmBuy && artDetail.id != null">
        <div class="header-box">
          <div class="title">请确认购买信息</div>
          <div class="close-btn">
            <el-button
              class="close-btn"
              plain
              size="small"
              icon="el-icon-close"
              circle
              @click="$store.dispatch('showComfirmBuy', false)"
            ></el-button>
          </div>
        </div>
        <div class="main-box">
          <div class="left-main">
            <div class="cover-box">
              <img :src="artDetail.cover_hash | ipfsHash" alt="" />
            </div>
            <div class="art-name">{{ artDetail.title }}</div>
            <div
              class="col-container"
              v-if="artDetail.array_id != null"
              @click="$router.push('/collection/' + artDetail.array_id)"
            >
              <div class="tip">合集</div>
              <div class="col-flex">
                <div class="col-cover-box">
                  <img :src="artDetail.array_logo | ipfsHash" alt="" />
                </div>
                <div class="col-name">{{ artDetail.array_name }}</div>
              </div>
            </div>
            <!-- 创作者和持有者信息 -->
            <div class="creater-owner-box">
              <div>
                <div class="tip">创作者</div>
                <div
                  class="user-box"
                  @click="$router.push('/user/' + artDetail.creator_address)"
                >
                  <div class="avatar">
                    <img
                      v-if="artDetail.creator_logo != null"
                      :src="artDetail.creator_logo | ipfsHash"
                      alt=""
                    />
                    <RandomAvatar
                      :user_address="artDetail.creator_address"
                      v-else
                    />
                  </div>
                  <div class="username" v-if="artDetail.creator_name != null">
                    @{{ artDetail.creator_name }}
                  </div>
                  <div class="username" v-if="artDetail.creator_name == null">
                    @{{ artDetail.creator_address | filterAddress }}
                  </div>
                </div>
              </div>
              <div>
                <div class="tip">目前持有者</div>
                <div
                  class="user-box"
                  @click="$router.push('/user/' + artDetail.owner)"
                >
                  <div class="avatar">
                    <img
                      v-if="artDetail.owner_logo != null"
                      :src="artDetail.owner_logo | ipfsHash"
                      alt=""
                    />
                    <RandomAvatar :user_address="artDetail.owner" v-else />
                  </div>
                  <div class="username" v-if="artDetail.owner_name != null">
                    @{{ artDetail.owner_name }}
                  </div>
                  <div class="username" v-if="artDetail.owner_name == null">
                    @{{ artDetail.owner | filterAddress }}
                  </div>
                </div>
              </div>
            </div>
          </div>
          <div class="right-main">
            <!-- 如果竞价，则展示输入数值 -->
            <!-- 最高价 -->
            <div class="now-price" v-if="artDetail.form_of_sale == '拍卖'">
              <div class="price-tip">当前最高价：</div>
              <div class="eth-icon">
                <img src="./images/ethereum.png" alt="" />
              </div>
              <div class="true-price" v-if="curAuction.length != 0">
                {{ curAuction["highestBid"] | weiToEth }}
              </div>
            </div>
            <div class="price" v-if="artDetail.form_of_sale == '拍卖'">
              <div class="price-tip tip-need">请出价：</div>
              <el-input
                class="price-input"
                v-model="bidPirce"
                placeholder="价格"
                type="number"
                :min="0"
              ></el-input>
              <el-select
                style="width: 100px"
                v-model="unit"
                placeholder="请选择"
              >
                <el-option
                  v-for="item in units"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </div>
            <div class="summary-box">
              <div class="summary-header">总计</div>
              <div class="summary-price">
                <div class="summary-price-tip">价格：</div>
                <div class="eth-icon">
                  <img src="./images/ethereum.png" alt="" />
                </div>
                <div
                  class="summary-true-price"
                  v-if="artDetail.form_of_sale == '定价出售'"
                >
                  {{ artDetail.price | weiToEth }}
                </div>
                <div
                  class="summary-true-price"
                  v-if="artDetail.form_of_sale == '拍卖'"
                >
                  {{ this.truePrice }}
                </div>
              </div>
              <!-- 费用 -->
              <div class="fees-box">
                <div class="fees-header">手续费</div>
                <div class="fees">
                  <div>平台费用</div>
                  <div class="gap"></div>
                  <div>2%</div>
                </div>
                <div class="fees">
                  <div>作者佣金</div>
                  <div class="gap"></div>
                  <div>{{ artDetail.commission }}%</div>
                </div>
              </div>
              <!-- 按钮组 -->
              <div class="btn-group">
                <div class="right-box">
                  <div
                    class="comfirm-btn btn"
                    @click="buyArt"
                    v-if="artDetail.form_of_sale == '定价出售'"
                  >
                    购买
                  </div>
                  <div
                    class="comfirm-btn btn"
                    @click="bidArt"
                    v-if="artDetail.form_of_sale == '拍卖'"
                  >
                    出价
                  </div>
                  <div
                    class="cansel-btn btn"
                    @click="$store.dispatch('showComfirmBuy', false)"
                  >
                    取消
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </transition>
  </div>
</template>

<script>
import { mapState } from "vuex";
import getAbi from "@/utils/contractAbi";
import Web3 from "web3";
export default {
  name: "ComfirmBuy",
  computed: {
    ...mapState({
      isShowComfirmBuy: (store) => store.popPanel.isShowComfirmBuy,
      artDetail: (store) => store.artDetail.artDetail,
    }),

    // 实际价格
    truePrice() {
      if (this.unit == "ETH") {
        return this.bidPirce;
      } else if (this.unit == "Wei") {
        this.bidPirce = parseInt(this.bidPirce).toString();
        return Web3.utils.fromWei(this.bidPirce, "ether");
      }
    },
  },
  data() {
    return {
      bidPirce: 0,
      unit: "ETH",
      units: [
        { label: "ETH", value: "ETH", selected: true },
        { label: "Wei", value: "Wei", selected: false },
      ],

      // 当前拍卖会信息
      curAuction: [],
    };
  },
  inject: ["reload"],

  watch: {
    artDetail: {
      immediate: true,
      async handler(newValue) {
        if (newValue.form_of_sale == "拍卖") {
          let abi = await getAbi();
          abi.methods
            .getCurAunction(newValue.nft_id)
            .call()
            .then((res) => (this.curAuction = res))
            .catch(console.log);
        }
      },
    },
  },
  methods: {
    // 确认购买
    async buyArt() {
      // nftId、价格
      let { nft_id, price } = this.artDetail;
      // user_address
      let user_address = this.$store.getters.user_address;
      // 获取合约
      console.log(nft_id, user_address, price);
      let abi = await getAbi();
      abi.methods
        .buyWorks(nft_id)
        .send({ from: user_address, value: price })
        .then((res) => {
          this.$message.success("交易成功");
          this.$store.dispatch("showComfirmBuy", false);
          // 刷新页面
          this.reload();
          // this.$router.go(0)
        })
        .catch(() => {
          this.$message.error("错误：请检查钱包状态");
        });
    },

    // 出价
    async bidArt() {
      // 校验
      // 是否为0
      if (this.bidPirce == 0) {
        this.$message.error("清输入价格");
        return;
      }
      // 转换为wei单位
      // console.log(this.truePrice)
      let truePriceWei = Web3.utils.toWei(this.truePrice.toString(), "ether");
      // 比价
      if (parseInt(truePriceWei) <= parseInt(this.curAuction["highestBid"])) {
        // 出价不够
        this.$message.error("出价必须比最高价高");
        return;
      }

      // nftId、价格
      let { nft_id } = this.artDetail;

      let user_address = this.$store.getters.user_address;
      // 获取合约
      let abi = await getAbi();
      abi.methods
        .bidForWorks(nft_id)
        .send({ from: user_address, value: truePriceWei })
        .then((res) => {
          console.log(res);
          this.$message.success("交易成功");
          this.$store.dispatch("showComfirmBuy", false);
          // 刷新页面
          this.reload();
          // this.$router.go(0)
        })
        .catch(() => {
          this.$message.error("错误：请检查钱包状态");
        });
    },
  },
};
</script>

<style lang='less'>
.comfirm-enter,
.comfirm-leave-to {
  transform: translateY(50vh);
}
.comfirm-enter-active,
.comfirm-leave-active {
  transition: all 0.5s;
}
#comfirm-buy {
  position: fixed;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  background: rgba(0, 0, 0, 0.2);
  z-index: 100;
  display: flex;
  align-items: center;
  justify-content: center;
  .container {
    background: #fff;
    padding: 30px;
    border-radius: 10px;
    .header-box {
      margin: 0;
      margin-bottom: 20px;
      display: flex;
      justify-content: space-between;
      align-items: center;
      .title {
        font-size: 20px;
        font-weight: bold;
      }
    }
    .main-box {
      display: flex;
      .left-main {
        .tip {
          font-size: 14px;
          margin-bottom: 5px;
          color: #999;
        }
        .cover-box {
          height: 200px;
          img {
            height: 100%;
          }
        }
        .col-container {
          margin-top: 10px;
          .col-flex {
            cursor: pointer;
            display: flex;
            align-items: center;
            .col-cover-box {
              width: 30px;
              height: 30px;
              img {
                border-radius: 5px;
                width: 100%;
                height: 100%;
                object-fit: cover;
              }
            }
            .col-name {
              margin-left: 10px;
              font-size: 16px;
            }
          }
        }
        .art-name {
          margin-top: 10px;
          font-size: 18px;
          font-weight: bold;
        }
        .art-price {
          font-size: 16px;
          margin-top: 10px;
          color: #333;
        }
        .creater-owner-box {
          margin-top: 20px;
          display: flex;
          .user-box {
            margin-right: 30px;
            margin-top: 10px;
            display: flex;
            align-items: center;
            box-shadow: 0px 8px 10px rgba(0, 0, 0, 0.05);
            padding: 10px;
            border-radius: 30px;
            cursor: pointer;
            .username {
              margin-left: 10px;
              font-size: 14px;
            }
            .avatar {
              width: 30px;
              height: 30px;
              border-radius: 50%;
              overflow: hidden;
              img {
                width: 100%;
                height: 100%;
                object-fit: cover;
              }
            }
          }
        }
      }
      .right-main {
        margin-left: 30px;
        padding: 20px;
        border-radius: 10px;
        width: 400px;
        .now-price {
          padding: 20px 0;
          display: flex;
          align-items: center;
          .eth-icon {
            height: 15px;
            width: 15px;
            img {
              width: 100%;
              height: 100%;
            }
          }
          .price-tip {
            font-size: 14px;
            color: #666;
            white-space: nowrap;
          }
          .true-price {
            margin-left: 10px;
            font-size: 18px;
          }
        }
        .price {
          display: flex;
          align-items: center;
          margin-bottom: 35px;
          .price-tip {
            white-space: nowrap;
          }
          .price-input {
            width: 180px;
          }
        }
        .summary-box {
          .summary-header {
            padding-bottom: 10px;
            border-bottom: 1px solid #eee;
          }
          .summary-price {
            padding: 20px 0;
            display: flex;
            align-items: center;
            .eth-icon {
              height: 15px;
              width: 15px;
              img {
                width: 100%;
                height: 100%;
              }
            }
            .summary-price-tip {
              margin-left: 10px;
              font-size: 14px;
              color: #666;
              width: 50px;
            }
            .summary-true-price {
              margin-left: 10px;
              font-size: 18px;
            }
          }
          .summary-session-box {
            padding: 10px 0;
            border-top: 1px solid #eee;
            .summary-session-tip {
              font-size: 14px;
              color: #666;
            }
            .summary-session-text {
              margin-top: 5px;
              font-size: 16px;
            }
          }
          .fees-box {
            padding-top: 10px;
            border-top: 1px solid #eee;
            .fees-header {
              font-size: 14px;
            }
            .fees {
              color: #666;
              margin-top: 10px;
              display: flex;
              align-items: center;
              font-size: 12px;
              .gap {
                flex: 1;
                border-bottom: 1px dashed #666;
                margin: 0 10px;
              }
            }
          }

          .btn-group {
            margin-top: 20px;
            border-top: 1px solid #eee;
            padding-top: 20px;
            display: flex;
            align-items: center;
            justify-content: space-between;
            .right-box {
              display: flex;
              .btn {
                cursor: pointer;
                padding: 8px 20px;
                margin-right: 10px;
                border-radius: 99px;
              }
              .btn:hover {
                opacity: 0.7;
              }
              .comfirm-btn {
                background: var(--themeColor4);
                color: #fff;
              }
              .cansel-btn {
                border: 1px solid #eee;
                color: #333;
              }
            }
          }
        }
      }
    }
  }
}
</style>